package com.note.chh.notebook.Uitls;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * SharedPreferences封装类SPUtils
 * @author Administrator
 *
 */
public class SPUtils
{
  /**
   * 保存在手机里面的文件名
   */
  public static final String FILE_NAME = "share_data";

  /**
   * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
   *
   * @param context
   * @param key
   * @param object
   */
  public static void put(Context context, String key, Object object)
  {

      SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
              Context.MODE_PRIVATE);
      Editor editor = sp.edit();

      if (object instanceof String)
      {
          editor.putString(key, (String) object);
      } else if (object instanceof Integer)
      {
          editor.putInt(key, (Integer) object);
      } else if (object instanceof Boolean)
      {
          editor.putBoolean(key, (Boolean) object);
      } else if (object instanceof Float)
      {
          editor.putFloat(key, (Float) object);
      } else if (object instanceof Long)
      {
          editor.putLong(key, (Long) object);
      } else
      {
          editor.putString(key, object.toString());
      }

      SharedPreferencesCompat.apply(editor);
  }

  /**
   * 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值
   *
   * @param context
   * @param key
   * @param defaultObject
   * @return
   */
  public static Object get(Context context, String key, Object defaultObject)
  {
      SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
              Context.MODE_PRIVATE);

      if (defaultObject instanceof String)
      {
          return sp.getString(key, (String) defaultObject);
      } else if (defaultObject instanceof Integer)
      {
          return sp.getInt(key, (Integer) defaultObject);
      } else if (defaultObject instanceof Boolean)
      {
          return sp.getBoolean(key, (Boolean) defaultObject);
      } else if (defaultObject instanceof Float)
      {
          return sp.getFloat(key, (Float) defaultObject);
      } else if (defaultObject instanceof Long)
      {
          return sp.getLong(key, (Long) defaultObject);
      }

      return null;
  }

  /**
   * 移除某个key值已经对应的值
   * @param context
   * @param key
   */
  public static void remove(Context context, String key)
  {
      SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
              Context.MODE_PRIVATE);
      Editor editor = sp.edit();
      editor.remove(key);
      SharedPreferencesCompat.apply(editor);
  }

  /**
   * 清除所有数据
   * @param context
   */
  public static void clear(Context context)
  {
      SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
              Context.MODE_PRIVATE);
      Editor editor = sp.edit();
      editor.clear();
      SharedPreferencesCompat.apply(editor);
  }

  /**
   * 查询某个key是否已经存在
   * @param context
   * @param key
   * @return
   */
  public static boolean contains(Context context, String key)
  {
      SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
              Context.MODE_PRIVATE);
      return sp.contains(key);
  }

  /**
   * 返回所有的键值对
   *
   * @param context
   * @return
   */
  public static Map<String, ?> getAll(Context context)
  {
      SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
              Context.MODE_PRIVATE);
      return sp.getAll();
  }

  /**
   * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
   *
   * @author zhy
   *
   */
  private static class SharedPreferencesCompat
  {
      private static final Method sApplyMethod = findApplyMethod();

      /**
       * 反射查找apply的方法
       * @return
       */
      @SuppressWarnings({ "unchecked", "rawtypes" })
      private static Method findApplyMethod()
      {
          try
          {
              Class clz = Editor.class;
              return clz.getMethod("apply");
          } catch (NoSuchMethodException e)
          {
          }

          return null;
      }

      /**
       * 如果找到则使用apply执行，否则使用commit
       *
       * @param editor
       */
      public static void apply(Editor editor)
      {
          try
          {
              if (sApplyMethod != null)
              {
                  sApplyMethod.invoke(editor);
                  return;
              }
          } catch (IllegalArgumentException e)
          {
          } catch (IllegalAccessException e)
          {
          } catch (InvocationTargetException e)
          {
          }
          editor.commit();
      }
  }

//-------------------------------------使用sp存储list集合-------------------------------------------------------------

  //将list集合转换成字符串

  public static String SceneList2String(List SceneList) throws IOException {
      // 实例化一个ByteArrayOutputStream对象，用来装载压缩后的字节文件。
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      // 然后将得到的字符数据装载到ObjectOutputStream
      ObjectOutputStream objectOutputStream = new ObjectOutputStream(
              byteArrayOutputStream);
      // writeObject 方法负责写入特定类的对象的状态，以便相应的 readObject 方法可以还原它
      objectOutputStream.writeObject(SceneList);
      // 最后，用Base64.encode将字节文件转换成Base64编码保存在String中
      String SceneListString = new String(Base64.encode(
              byteArrayOutputStream.toByteArray(), Base64.DEFAULT));
      // 关闭objectOutputStream
      objectOutputStream.close();
      return SceneListString;
  }

  // 将字符串转换成list集合
  @SuppressWarnings("unchecked")
  public static List String2SceneList(String SceneListString) throws StreamCorruptedException, IOException,
          ClassNotFoundException {
      byte[] mobileBytes = Base64.decode(SceneListString.getBytes(),
              Base64.DEFAULT);
      ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
              mobileBytes);
      ObjectInputStream objectInputStream = new ObjectInputStream(
              byteArrayInputStream);
      List SceneList = (List) objectInputStream.readObject();
      objectInputStream.close();
      return SceneList;
  }
  //存储list集合                str1文件对应的key值            str2存储数据对应的key值
  public static void SaveList(Context context, String str1, String str2, List list){
      SharedPreferences sp = context.getSharedPreferences(str1, Context.MODE_PRIVATE);
      Editor edit = sp.edit();
      try {
          //将list集合转成字符串
          String listStr = SceneList2String(list);
          //存储
          edit.putString(str2, listStr);
          edit.commit();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }

  //获取list集合             str1文件对应的key值            str2存储数据对应的key值
  public static List GetList(Context context, String str1, String str2){
      SharedPreferences sp = context.getSharedPreferences(str1, Context.MODE_PRIVATE);
      String liststr = sp.getString(str2, "");
      if (!TextUtils.isEmpty(liststr)) {
          try {
              List list = String2SceneList(liststr);
              return list;
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
      return null;
  }

}
